package com.droid.mvvmlib.router;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.droid.mvvmlib.log.Logcat;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author zhyuc
 * @since 2019/10/26 9:59
 */
public class RouterImpl implements IRouter {

    private final String TAG = "RouterImpl";

    private static volatile RouterImpl mInstance;

    public static RouterImpl getInstance() {
        if (mInstance == null) {
            synchronized (RouterImpl.class) {
                if (mInstance == null) {
                    mInstance = new RouterImpl();
                }
            }
        }
        return mInstance;
    }

    private RouterImpl() {
    }

    @Override
    public void startActivity(Activity context, @NonNull String path) {
        startActivity(context, path, -1);
    }

    @Override
    public void startActivity(Activity context, @NonNull String path, int flags) {
        startActivity(context, path, null, flags);
    }

    @Override
    public void startActivity(Activity context, @NonNull String path, @Nullable Bundle bundle, int flags) {
        startActivity(context, path, bundle, flags, null, -1);
    }

    @Override
    public void startActivity(Activity context, @NonNull String path, int flags, int reqCode) {
        startActivity(context, path, flags, reqCode);
    }

    @Override
    public void startActivity(Activity context, @NonNull String path, @Nullable Bundle bundle, int flags, int reqCode) {
        startActivity(context, path, bundle, flags, null, reqCode);
    }

    @Override
    public void startActivity(Activity context, @NonNull String path, @Nullable Bundle bundle, int flags, IRouterCallBack callBack, int reqCode) {
        Postcard postcard = ARouter.getInstance().build(path);
        if (flags != -1 && (flags != Intent.FLAG_ACTIVITY_CLEAR_TASK
                && flags != Intent.FLAG_ACTIVITY_CLEAR_TOP
                && flags != Intent.FLAG_ACTIVITY_NEW_TASK)) {
            Logcat.e(TAG, "flags is invalid argument");
            return;
        }
        if (flags != -1) {
            postcard.withFlags(flags);
        }

        if (bundle != null) {
            postcard.with(bundle);
        }

        if (callBack != null && callBack instanceof NavigationCallback) {
            if (reqCode >= 0) {
                postcard.navigation(context, reqCode, (NavigationCallback) callBack);
            } else {
                postcard.navigation(context, (NavigationCallback) callBack);
            }
        } else {
            if (reqCode >= 0) {
                postcard.navigation(context, reqCode);
            } else {
                postcard.navigation(context);
            }
        }
    }
}
